package jzqb.dao.impl;

import cnki.tpi.base.DataContext;
import cnki.tpi.base.DataSourceManager;
import cnki.tpi.kbatis.sqlsession.SqlSession;
import cnki.tpi.kbatis.utils.DataSourceUtil;
import com.kbase.jdbc.ConnectionImpl;
import haha.life.common.BelongToSqlUtils;
import haha.life.normal.*;
import jzqb.bo.AdminUserInfoBo;
import jzqb.common.Result;
import jzqb.dao.AdminUserInfoDao;
import jzqb.po.*;
import kbase.KBaseClient;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class AdminUserInfoDaoImpl implements AdminUserInfoDao {

    @Autowired
    private DataSourceManager kbaseDs;

    @Autowired
    private DataContext dataContext;

    @Value("${filePath.recPath}")
    private String recPath;


    @Override
    public Result login(String id, String pwd) {
        AdminLoginPo adminloginpo = new AdminLoginPo();
        adminloginpo.setId(id);
        adminloginpo.setPwd(pwd);

        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        //dao文件.sql的id
        String statementId = "jzqb.dao.AdminUserInfoDao.getSaltPwd";
        AdminUserPo po = sqlSession.selectOne(statementId,adminloginpo,false);
        if (po != null){
            String salt = po.getSalt();
            String pwdHash = po.getPwd();
            System.out.println("数据库中的密码:"+pwdHash);
            Boolean check =  PwdUtils.checkPwd(pwd,pwdHash,salt);
            if (check){

                String changedPwd = po.getPwdChangeFlag();
                if ("1".equals(changedPwd)){
                    String access_token = TokenUtils.generateToken(id);
                    Map<String, String> dictionary = new HashMap<String, String>();
                    dictionary.put("token", access_token);

                    AdminLayoutPo layoutpo = new AdminLayoutPo();
                    layoutpo.setId(id);
                    layoutpo.setName(po.getName());

                    dictionary.put("userinfo", CommonConvertUtils.getBeanToJson(layoutpo));
                    return Result.succ("登录成功",dictionary);
                }else{
                    return Result.succ732("1");
                }



            }else{
                return Result.fail("密码错误");
            }
        }else {
            return Result.fail("账号不存在");
        }
    }

    @Override
    public List<AdminUserPo> cutList(AdminUserInfoBo AdminuserinfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getUserInfoList";
        List<AdminUserPo> cutList = sqlSession.selectList(statementId, AdminuserinfoBo,false);
        return cutList;
    }

    @Override
    public long cutCount(AdminUserInfoBo AdminuserinfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getUserInfoListCount";
        long num=sqlSession.getCount(statementId,AdminuserinfoBo);
        return num;
    }

    @Override
    public List<AdminUserPo> findAllUser() {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.findAllUser";
        return sqlSession.selectList(statementId,null,false);
    }

    @Override
    public List<AdminUserPo> findUsersByDeptNo(String deptNo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.findUsersByDeptNo";
        return sqlSession.selectList(statementId,deptNo,false);
    }

    @Override
    public List<AdminUserPo> getUsrByName(String userName) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getUsrByName";
        return sqlSession.selectList(statementId,userName,false);
    }


    @Override
    public Result resetPwd(String id,String pwd) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getSaltPwd";
        AdminLoginPo tempPo = new AdminLoginPo();
        tempPo.setId(id);
        AdminUserPo po = sqlSession.selectOne(statementId,tempPo,false);
        String salt = po.getSalt();
        String newPwd = PwdUtils.generatePwdByID_Salt(pwd,salt);
        po.setPwd(newPwd);
        String statementId_ = "jzqb.dao.AdminUserInfoDao.resetPwd";

        boolean res_1 =sqlSession.executeInsert(statementId_,po);
        if (res_1){
            return Result.succ("修改密码成功");
        }else{
            return Result.fail("修改密码失败");
        }

    }

    @Override
    public AdminUserPo findUserById(String id) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.findUserById";
        return sqlSession.selectOne(statementId,id,false);
    }

    @Override
    public Result mute(AdminUserInfoBo adminUserInfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.mute";
        if (adminUserInfoBo.getMuteFlag().equals("true")){
            adminUserInfoBo.setMuteFlag("1");
        }else {
            adminUserInfoBo.setMuteFlag("");
        }
        boolean res =sqlSession.executeInsert(statementId,adminUserInfoBo);

        if (res){
            return Result.succ("禁言状态修改成功");
        }else{
            return Result.fail("禁言状态修改失败");
        }
    }


    @Override
    public boolean  belongToPermissionGroup(String userid,String PermissionGroupID){

        // 1 根据userid获取用户对象
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId_1 = "jzqb.dao.AdminUserInfoDao.findUserById";
        AdminUserPo userPo = sqlSession.selectOne(statementId_1, userid, false);
        //2 从用户对象中获取用户的所有部门
        ArrayList<String> deps = new ArrayList<String>();
        if (!userPo.getDepartmentid().equals("")){
            for (String depId:userPo.getDepartmentid().split(";")) {
                deps.add(depId);
            }
        }

        //3 通过id和部门获取此人的权限组id的集合
        String statementId_2 = "jzqb.dao.AdminPermissionDao.getQXZByID_deps";
        ArrayList<String> conditionList = new ArrayList<String>();
        conditionList.add("用户成员 = " + "'" + userid + "'");
        for (String depid:deps) {
            conditionList.add("部门成员 =" + "'" + depid + "'");
        }
        String condition = String.join(" or ",conditionList);

        List<AdminPermissionGroupPo> adminPermissionGroupPoList =  sqlSession.selectList(statementId_2, condition,false);

        boolean res = false;
        for (AdminPermissionGroupPo permissionPo:adminPermissionGroupPoList) {
            String id = permissionPo.getPermissionGroupID();
            if (PermissionGroupID.equals(id)){
                res = true;
                break;
            }
        }
        return res;
    }

    @Override
    public void insertLoginRecord(AdminLoginLogPo adminLoginLogPo){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();

        //由于kabse不区分大小写,所以,如果用户的账户是aaa,当他通过AAA进行登录时,
        //也是允许的,但是此时的登录日志不应该记录为AAA,而是记录通过AAA在数据库中查询得到的
        //账号进行保存
        String statementId_1 = "jzqb.dao.AdminUserInfoDao.findUserById";
        AdminUserPo userPo = sqlSession.selectOne(statementId_1, adminLoginLogPo.getUserid(), false);
        adminLoginLogPo.setUserid(userPo.getId());

        String statementId = "jzqb.dao.AdminUserInfoDao.insertLoginLog";
        boolean res =sqlSession.executeInsert(statementId,adminLoginLogPo);
    }

    @Override
    public Result initPwd(String id,String pwd,String newPwd,String newPwdConfirm){
        //1 判断两次新密码是否相同 是-->2 否-->返回
        //2 账号+旧密码 是否能够匹配到数据库 是-->3 否-->返回
        //3 修改密码,修改密码标志位
        //4 返回token

        if (!newPwd.equals(newPwdConfirm)){
            return Result.fail("新旧密码不一致");
        }

        AdminLoginPo adminloginpo = new AdminLoginPo();
        adminloginpo.setId(id);
        adminloginpo.setPwd(pwd);

        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getSaltPwd";
        AdminUserPo po = sqlSession.selectOne(statementId,adminloginpo,false);
        if (po != null){
            String salt = po.getSalt();
            String pwdHash = po.getPwd();
            Boolean check =  PwdUtils.checkPwd(pwd,pwdHash,salt);
            if (check){

                String newPwdHash = PwdUtils.generatePwdByID_Salt(newPwd,salt);
                po.setPwd(newPwdHash);
                String statementId_ = "jzqb.dao.AdminUserInfoDao.initPwd";
                boolean res_1 =sqlSession.executeInsert(statementId_,po);
                if (res_1){
                    String access_token = TokenUtils.generateToken(id);
                    Map<String, String> dictionary = new HashMap<String, String>();
                    dictionary.put("token", access_token);

                    AdminLayoutPo layoutpo = new AdminLayoutPo();
                    layoutpo.setId(id);
                    layoutpo.setName(po.getName());

                    dictionary.put("userinfo", CommonConvertUtils.getBeanToJson(layoutpo));
                    return Result.succ("登录成功",dictionary);
                }else{
                    return Result.fail("修改失败");
                }
            }else{
                return Result.fail("密码错误");
            }
        }else {
            return Result.fail("账号不存在");
        }
    }

    @Override
    public AdminUserInfoBo basicInfo(String userid){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.basicInfo";
        AdminUserInfoBo obj = sqlSession.selectOne(statementId,userid,false);
        return obj;
    };

    @Override
    public boolean isUserIDExist(String id){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.isUserIDExist";
        AdminUserInfoBo obj = sqlSession.selectOne(statementId,id,false);
        if (obj==null){
            return false;
        }else{
            return true;
        }
    };

    @Override
    public boolean addUser(AdminUserPo userPo,String type){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        if (type.equals("add")){
            String statementId = "jzqb.dao.AdminUserInfoDao.addUser";
            boolean res = sqlSession.executeInsert(statementId,userPo);
            return res;
        }else if (type.equals("edit")){
            String statementId = "jzqb.dao.AdminUserInfoDao.editUser";
            boolean res = sqlSession.executeInsert(statementId,userPo);
            return res;
        }else {
            return false;
        }

    };

    @Override
    public boolean deleteUser(AdminUserPo userPo){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.deleteUser";
        boolean res = sqlSession.executeInsert(statementId,userPo);
        return res;

    };

    @Override
    public List<String> getAllFunctionPermissionGroupIdsOfUser(String userid){
        /*
        *        userid(String)------→
        *           ↓(查询得到)       | 查询得到
        *         用户对象           |---------->获得此人所在权限组集合
        *           ↓(直接获取)     |
        *     用户的所有部门--------→
        * */
        //1.通过id获取用户对象
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String getUserObj_sql = "jzqb.dao.AdminUserInfoDao.findUserById";
        AdminUserPo userPo = sqlSession.selectOne(getUserObj_sql, userid, false);

        //2.通过用户对象获取该用户的所有部门
        ArrayList<String> deps = new ArrayList<String>();
        if (!userPo.getDepartmentid().equals("")){
            for (String depId:userPo.getDepartmentid().split(";")) {
                deps.add(depId);
            }
        }

        //3 通过id和部门获取此人的权限组id的集合
        String statementId_2 = "jzqb.dao.AdminPermissionDao.getQXZByID_deps";
        ArrayList<String> conditionList = new ArrayList<String>();
        conditionList.add("用户成员 = " + "'" + userid + "'");
        for (String depid:deps) {
            conditionList.add("部门成员 =" + "'" + depid + "'");
        }
        String condition = String.join(" or ",conditionList);

        List<AdminPermissionGroupPo> adminPermissionGroupPoList =  sqlSession.selectList(statementId_2, condition,false);

        List<String> res = new ArrayList<>();
        for (AdminPermissionGroupPo po:adminPermissionGroupPoList){
            res.add(po.getPermissionGroupID());
        }
        return res;

    };

    @Override
    public Result changeMyPwd(AdminLoginPo adminloginpo){
        /*
        *
        * 用户id --查询数据库-→用户对象存在--->对象的salt+明文密码==对象的密文密码-->对象的salt+新密码，生成新密文密码-->修改用户密码 code=1200，“密码修改成功”
        *                            |      |对象的salt+明文密码!=对象的密文密码  code=1201，“密码验证失败”
        *                            |
        *                            |--→用户对象不存在 code=1201，“用户不存在”
        * */
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        //dao文件.sql的id
        String statementId = "jzqb.dao.AdminUserInfoDao.getSaltPwd";
        AdminUserPo po = sqlSession.selectOne(statementId,adminloginpo,false);
        if (po != null){
            String salt = po.getSalt();
            String pwdHash = po.getPwd();
            Boolean check =  PwdUtils.checkPwd(adminloginpo.getPwd(),pwdHash,salt);
            if (check){
                String newPwd = PwdUtils.generatePwdByID_Salt(adminloginpo.getNewpwd(),salt);
                adminloginpo.setNewpwd(newPwd);
                String changeMyPwd = "jzqb.dao.AdminUserInfoDao.changeMyPwd";
                boolean res = sqlSession.executeInsert(changeMyPwd,adminloginpo);
                if (res)
                {
                    return Result.DiyCode(1200,"密码修改成功");
                }else
                {
                    return Result.DiyCode(1201,"密码修改失败");
                }
            }else{
                return Result.DiyCode(1202,"密码验证失败");
            }
        }else {
            return Result.DiyCode(123,"用户不存在");
        }
    }


    @Override
    public List<AdminUserPo> getAllUser(){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getAllUser";
        return sqlSession.selectList(statementId,null,false);
    }


    /**
     * 复制文件,并删除原文件
     * @param s 文件的临时位置
     * @param t 文件的数据库目标位置
     * @return 执行结果
     */
    public Boolean moveTempFileToDBFile(String s, String t,String...arg) {
        ConnectionImpl conn = null;
        try {
            conn = (ConnectionImpl) this.kbaseDs.getConnection();
            int hCon = conn.getConnectionHset();
            KBaseClient kBaseClient = conn.getKbaseClient();
            //int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            String tPath = t.substring(0, t.lastIndexOf("\\"));
            String sPath = s.substring(0, s.lastIndexOf("\\"));
            int tempRet = kBaseClient.KBase_MakeDir(hCon, tPath);
            int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            if (nRet < 0) {
                return false;
            }
            else if (nRet == 0){
                //写入文件到DB正常,删除临时文件
                if (arg.length==0){
                    FileUtil.deleteFile(s);
                }else{
                    if (arg[0].equals("notDeleteDir")){}
                }
                return true;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        finally {
            try {
                if (conn != null && !conn.isClosed())
                    conn.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    @Override
    public boolean writeExcelData(JSONArray jsonArray) throws IOException {
        // 1 生成REC内容
        String recStr ="";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject lineObject = jsonArray.getJSONObject(i);
            String userid = lineObject.get("userid").toString();
            String userName = lineObject.get("userName").toString();
            String orgId = lineObject.get("orgId").toString();
            String mobile = lineObject.get("mobile").toString();
            String email = lineObject.get("email").toString();

            String salt = RandomUtils.getRandomString(4);
            String pwd = PwdUtils.generatePwdByID_Salt("123456",salt);
            recStr += "<REC>\n";
            recStr += String.format("<ID>=%s\n",userid);
            recStr += String.format("<姓名>=%s\n",userName);
            recStr += String.format("<所属部门>=%s\n",orgId);
            recStr += String.format("<电话>=%s\n",mobile);
            recStr += String.format("<邮箱>=%s\n",email);
            recStr += String.format("<密码>=%s\n",pwd);
            recStr += String.format("<SALT>=%s\n",salt);
        }

        // 2 先把rec文件保存在 springboot服务器(文件夹不必提前新建)
        File recFile = new File(recPath + "\\" + "REC_user.txt");
        if(!recFile.getParentFile().exists()){
            recFile.getParentFile().mkdirs();
        }
        recFile.createNewFile();
        String  recFilePath = recFile.toString();
        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(recFilePath), "GB2312");
        BufferedWriter writer = new BufferedWriter(write);
        writer.write(recStr);
        writer.close();

        // 3 再把rec文件从springboot服务器 复制到 kbase服务器,复制后,删除springboot端文件(kbase端,文件夹不必提前新建)
        boolean res1 = moveTempFileToDBFile(recFilePath,recFilePath);

        // 4 生成优化键脚本内容
        String tableName = "YQTYHB";
        String Key = "ID";
        String script_content = String.format(
                "CREATE OPTIMIZEKEY %s ON TABLE %s\n" +
                "\n" +
                "EXCLUSIVE INSERT INTO TABLE %s WITH KEY=%s\n" +
                "\tINFILE \"%s\"\n" +
                "\n" +
                "DROP OPTIMIZEKEY %s ON TABLE %s"
                ,Key,tableName
                ,tableName,Key
                ,recFilePath
                ,Key,tableName
                );

        // 5 先把脚本文件保存在 springboot服务器(文件夹不必提前新建)
        File scriptFile = new File(recPath + "\\" + "REC_user_script.txt");
        if(!scriptFile.getParentFile().exists()){
            scriptFile.getParentFile().mkdirs();
        }
        scriptFile.createNewFile();
        String  scriptFilePath = scriptFile.toString();
        OutputStreamWriter write_script = new OutputStreamWriter(new FileOutputStream(scriptFilePath), "GB2312");
        BufferedWriter writer_script = new BufferedWriter(write_script);
        writer_script.write(script_content);
        writer_script.close();

        // 6 再把脚本文件从springboot服务器 复制到 kbase服务器,复制后,删除springboot端文件(kbase端,文件夹不必提前新建)
        boolean res2 = moveTempFileToDBFile(scriptFilePath,scriptFilePath);

        // 7 运行脚本
        String sql = String.format("DBUM UPDATE TABLE BY \"%s\"",scriptFilePath);
        int excuteRECscript = dataContext.excuteSql(sql);
        if (excuteRECscript==0){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public List<AdminUserPo> getUserNameById(String recorderId) {
        String[] ztjArr= recorderId.split(",");
        String userSql = BelongToSqlUtils.getBelongToSql(ztjArr, "ID");
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getUserNameById";
        return sqlSession.selectList(statementId,userSql,false);
    }

    @Override
    public AdminUserInfoBo getUserById(String userId) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.getUserById";
        return sqlSession.selectOne(statementId,userId,false);
    }

    @Override
    public Boolean updateUserInfo(AdminUserInfoBo userPo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminUserInfoDao.updateUserInfo";
        return sqlSession.executeUpdate(statementId,userPo);
    }
}
